package com.toprs.base.config

import com.toprs.base.annotation.ProjectLog
import com.toprs.base.annotation.Slf4j2
import com.toprs.base.annotation.Slf4j2.Companion.log
import com.toprs.base.result.Result
import jakarta.servlet.http.HttpServletRequest
import org.aspectj.lang.JoinPoint
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.AfterReturning
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.springframework.stereotype.Component
import org.springframework.web.context.request.RequestAttributes
import org.springframework.web.context.request.RequestContextHolder
import java.util.*


@Aspect
@Component
@Slf4j2
class ProjectLogAspect(val request: HttpServletRequest) {


    @Around("@annotation(com.toprs.base.annotation.ProjectLog)&& @annotation(log)")
    fun projectLog(joinPoint: ProceedingJoinPoint, log: ProjectLog) {
        println(request.inputStream)
    }

    @AfterReturning(value = "within(com.toprs.*.controller.*)", returning = "rtv")
    fun afterReturningImp(joinPoint: JoinPoint?, rtv: Any) {
        val requestAttributes = RequestContextHolder.getRequestAttributes()!!
        val request = requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST) as HttpServletRequest?
        if (request != null) {

            val url = request.requestURI.lowercase(Locale.getDefault())

            if (url.contains("download")) {
                log.info("请求： Method:{} Url:{}", request.method, request.requestURI)
            } else {
//                val res = rtv.toString()
                if (rtv.javaClass.name.equals("com.toprs.base.result.Result")) {
                    log.info(
                        "请求： Method:{} Url:{} Result:{}",
                        request.method,
                        request.requestURI,
                        (rtv as Result<*>).msg
                    )
                } else {
                    log.info("请求： Method:{} Url:{}", request.method, request.requestURI)
                }
            }
        }
    }


}